package bz.ziro.kanbe.controller.mng.site;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;
import org.slim3.util.BeanUtil;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import bz.ziro.kanbe.dao.UserAgentDao;
import bz.ziro.kanbe.logic.FirstLogic;
import bz.ziro.kanbe.model.Site;
import bz.ziro.kanbe.model.UserAgent;
import bz.ziro.kanbe.util.KeyFactory;

/**
 * サイトの追加
 * @author Administrator
 *
 */
public class AddController extends Controller {

    private static final Logger logger = Logger.getLogger(AddController.class.getName());

    @Override
    public Navigation run() {


        Site site = new Site();
        BeanUtil.copy(request, site);

        Key key = KeyFactory.allocateSiteKey();
        site.setKey(key);

        try {
            //公開日の指定
            String publishDate = requestScope("workPublishDate");
            //存在した場合
            if ( publishDate != null && !publishDate.equals("") ) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        		site.setPublishDate(sdf.parse(publishDate));
            }
        } catch ( Exception ex ) {
            logger.severe(ex.getMessage());
        }
        
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        Date nowDate = new Date();
        //作成日を設定
        site.setCreateDate(nowDate);
        site.setCreator(user);

        List<Object> models = new ArrayList<Object>();
        models.add(site);
        
        UserAgent agent = UserAgentDao.findDefaultAgent();
        //頁のデータを作成
        FirstLogic.insertFirstPageData(site,agent,models);

        Transaction tx = Datastore.beginTransaction();
        Datastore.put(tx,models);
        tx.commit();

        return null;
    }
}
